﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.CustomerManagement;
using NopSolutions.NopCommerce.BusinessLogic.Orders;
using NopSolutions.NopCommerce.BusinessLogic.Payment;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.BusinessLogic.Shipping;
using NopSolutions.NopCommerce.BusinessLogic.Alesko;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Audit;

namespace NopSolutions.NopCommerce.Web
{
  public partial class OrderWizard : BaseNopFrontendPage
  {
    protected ShoppingCart cart = null;

    protected void Page_Load(object sender, EventArgs e)
    {
      CommonHelper.SetResponseNoCache(Response);

      if (!IsPostBack)
      {
        SetStep("Cart");
      }
    }

    public void SetStep(string step)
    {
      OrderProgressStep = OrderProgressControl.OrderProgressStep = step;
      string title = "";

      pnlShoppingCart.Visible = false;
      pnlAddress.Visible = false;
      pnlShipping.Visible = false;
      pnlPaymentType.Visible = false;

      switch (this.OrderProgressStep.ToLowerInvariant())
      {
        case "cart":
          {
            title = GetLocaleResourceString("PageTitle.ShoppingCart");
            pnlShoppingCart.Visible = true;
          }
          break;
        case "address":
          {
            title = GetLocaleResourceString("PageTitle.CheckoutShippingAddress");
            pnlAddress.Visible = true;

            if (DateGet != null)
              ctrlCheckoutShippingAddress.ctrlShippingAddress.dtDateGet.SelectedDate = DateGet;
          }
          break;
        case "shipping":
          {
            title = GetLocaleResourceString("PageTitle.CheckoutShippingMethod");
            pnlShipping.Visible = true;
            ctrlCheckoutShippingMethod.BindData();

            if (DeliveryId != -1)
              ctrlCheckoutShippingMethod.SelectedDelivery = ctrlCheckoutShippingMethod.DeliveryService.GetDeliveryById(DeliveryId);
            else
            {
              var defDelivery = ctrlCheckoutShippingMethod.DeliveryService.GetAllDeliveries();
              if (defDelivery.Count > 0)
              {
                ctrlCheckoutShippingMethod.SelectedDelivery = defDelivery[0];
                DeliveryId = defDelivery[0].DeliveryId;
              }
            }
            OrderSummaryControl1.BindData();
          }
          break;
        case "payment":
          {
              title = GetLocaleResourceString("PageTitle.CheckoutPaymentInfo");
              pnlPaymentType.Visible = true;
              PaymentTypeControl.BindData();

              if (PaymentTypeId != -1)
                PaymentTypeControl.SelectedPaymentType = ctrlCheckoutShippingMethod.PaymentTypeService.GetPaymentTypeById(PaymentTypeId);
              else
              {
                var defPaymentType = ctrlCheckoutShippingMethod.PaymentTypeService.GetAllPaymentTypes();
                if (defPaymentType.Count > 0)
                {
                  PaymentTypeControl.SelectedPaymentType = defPaymentType[0];
                  PaymentTypeId = defPaymentType[0].PaymentTypeId;
                }
              }
              OrderSummaryControl2.BindData();
          }
          break;
      }

      SEOHelper.RenderTitle(this, title, true);
    }

    protected void btnNextStepShipping_Click(object sender, EventArgs e)
    {
      if (DeliveryId == -1)
      {
        lblError.Text = "Необходимо указать вид доставки!";
        return;
      }

      SetStep("payment");
    }
    
    protected void btnBackShipping_Click(object sender, EventArgs e)
    {
      SetStep("address");
    }

    protected void btnNextStepPayment_Click(object sender, EventArgs e)
    {
        if (PaymentTypeControl.SelectedPaymentType == null)
        {
            lblError1.Text = "Необходимо указать способ оплаты!";
            return;
        }

        try
        {
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.IsRecurringPayment = false;
            paymentInfo.BillingAddress = NopContext.Current.User.BillingAddress;
            paymentInfo.ShippingAddress = ctrlCheckoutShippingAddress.ctrlShippingAddress.ShippingAddress;
            paymentInfo.CustomerLanguage = NopContext.Current.WorkingLanguage;
            paymentInfo.CustomerCurrency = NopContext.Current.WorkingCurrency;
            paymentInfo.PaymentMethodId = PaymentTypeControl.SelectedPaymentType.PaymentTypeId;
            
            int orderId = 0;
            Delivery delivery = this.DeliveryService.GetDeliveryById(DeliveryId);
            string result = this.OrderService.PlaceOrder(paymentInfo, paymentInfo.ShippingAddress,
                DateGet,
                ctrlCheckoutShippingAddress.ctrlShippingAddress.cbNotifiedSMSAboutOrder.Checked,
                ctrlCheckoutShippingAddress.ctrlShippingAddress.txtAddInfo.Text,
                delivery, NopContext.Current.User, Guid.NewGuid(), out orderId);
            var order = this.OrderService.GetOrderById(orderId);
            if (!String.IsNullOrEmpty(result))
            {
                lblError1.Text = Server.HtmlEncode(result);
                return;
            }
            else
            {
              OrderId = order.OrderId;  
              // PayPal
              if (PaymentTypeId == 2)
              {
                  //this.PaymentService.PostProcessPayment(order);
                  Response.Redirect("~/OrderWizardPayPalPaymentStarting.aspx?OrderGuid=" + order.OrderGuid.ToString());
              }
              else
                  Response.Redirect("~/OrderWizardResult.aspx?OrderGuid=" + order.OrderGuid.ToString());
            }
        }
        catch (Exception exc)
        {
            this.LogService.InsertLog(LogTypeEnum.OrderError, exc.Message, exc);
            lblError1.Text = Server.HtmlEncode(exc.ToString());
        }
        
    }

    protected void btnBackPayment_Click(object sender, EventArgs e)
    {
        if (PaymentTypeControl.SelectedPaymentType != null)
            PaymentTypeId = PaymentTypeControl.SelectedPaymentType.PaymentTypeId;

        SetStep("shipping");
    }


    public void RefreshDeliveryPrice()
    {
      this.DeliveryId = this.ctrlCheckoutShippingMethod.SelectedDelivery.DeliveryId;
      OrderSummaryControl1.BindData();
    }

    public void RefreshPaymentTypeFee()
    {
      this.PaymentTypeId = this.PaymentTypeControl.SelectedPaymentType.PaymentTypeId;
      OrderSummaryControl2.BindData();
    }

    public ShoppingCart Cart
    {
      get
      {
        if (cart == null)
        {
          cart = this.ShoppingCartService.GetCurrentShoppingCart(ShoppingCartTypeEnum.ShoppingCart);
        }
        return cart;
      }
    }

    public override PageSslProtectionEnum SslProtected
    {
      get
      {
        return PageSslProtectionEnum.Yes;
      }
    }

    public string OrderProgressStep
    {
      get
      {
        if (ViewState["OrderProgressStep"] == null)
          return "Cart";
        else
          return (string)ViewState["OrderProgressStep"];
      }
      set
      {
        ViewState["OrderProgressStep"] = value;
      }
    }

    public DateTime? DateGet
    {
        get
        {
            if (ViewState["DateGet"] == null)
                return null;
            else
                return (DateTime)ViewState["DateGet"];
        }
        set
        {
            ViewState["DateGet"] = value;
        }
    }

    public int DeliveryId
    {
        get
        {
          if (ViewState["DeliveryId"] == null)
            return -1;
          else
            return (int)ViewState["DeliveryId"];
        }
        set
        {
            ViewState["DeliveryId"] = value;
        }
    }

    public int PaymentTypeId
    {
      get
      {
        if (ViewState["PaymentTypeId"] == null)
          return -1;
        else
          return (int)ViewState["PaymentTypeId"];
      }
      set
      {
        ViewState["PaymentTypeId"] = value;
      }
    }

    public int OrderId
    {
      get
      {
        if (ViewState["OrderId"] == null)
          return -1;
        else
          return (int)ViewState["OrderId"];
      }
      set
      {
        ViewState["OrderId"] = value;
      }
    }

  }
}